import { defineStore } from 'pinia'
import { ref } from 'vue'
import { Time } from '@/utils/serverTime'
import { OperatorServerBrand } from '@/utils/index'

import { useStore } from '@/stores/index'
const indexStore = useStore()

interface UseWebSocket {
  socket: any
  readyState: number
  socketMessage: Record<string, any>
  isReconnect: boolean
  lockReconnect: boolean
}

export const WebsocketStore = defineStore('websocket', {
  state: (): UseWebSocket => {
    return {
      socket: null,
      readyState: 0,
      socketMessage: {},
      isReconnect: true, // 是否重连（主动断开是不重连）
      lockReconnect: false // 防止重复连接
    }
  },
  actions: {
    SET_SOCKET (socket: object) {
      this.socket = socket
    },
    SET_SOCKET_MESSAGE (socketMessage: any) {
      this.socketMessage = socketMessage
    },
    connectWebSocket () {
      if (this.lockReconnect) return
      this.lockReconnect = true
      this.isReconnect = true
      const CONNECT_TIME = 20000 // 重新连接间隔时间
      const PING_INTERVAL = 3000 // 心跳间隔，单位为毫秒
      const heartbeatMessage = 'ping' // 心跳消息
      const socket = ref(new WebSocket(OperatorServerBrand('socket')+'/api/v1/websocket/register'))
      this.SET_SOCKET(socket)
      setTimeout(() => {
        this.lockReconnect = false
      }, 4000)

      const heartNum = 50000 // 重新连接次数
      let intervalObj: any
      const heartCheckTask = () => {
        let countDown = heartNum
        intervalObj && clearInterval(intervalObj)
        intervalObj = setInterval(() => {
          this.socket.send(heartbeatMessage)
          countDown--
          if (countDown === 0) {
            clearInterval(intervalObj)
            this.socket.close()
          }
        }, PING_INTERVAL)
      }

      // 监听连接事件
      socket.value.onopen = (res:any) => {
        console.log('连接成功',res);
        heartCheckTask()
      }

      // 监听消息事件
      socket.value.onmessage = (event) => {
        try {
          if (event.data === 'pong') {
            heartCheckTask()
            return
          }
          if(event.data !='链接成功'){
            console.log(`推送消息: ${new Time().format()} ${event.data}`,event);
          }
          if(event.data == '货币修改'){
            indexStore.getCurrent() //货币汇总
          }
          if(event.data == '货币汇率修改'){
            indexStore.getExchange() //货币汇率汇总
          }
          if(event.data == '总代修改'){
            indexStore.getOperator() //总代汇总
          }
          if(event.data == '商户修改'){
            indexStore.getAgent() //商户汇总
          }
          if(event.data == '游戏修改'){
            indexStore.getGame() //游戏汇总
          }
          const message = JSON.parse(event.data)
          this.SET_SOCKET_MESSAGE(message)
        } catch (error) {}
      }

      // 监听关闭事件 断线重连
      socket.value.onclose = (error) => {
        console.log('连接断开',error);
        // 断线重连(主动断开不重连)
        if (this.isReconnect) {
          setTimeout(() => {
            this.connectWebSocket()
          }, CONNECT_TIME)
        }
      }

      // 连接错误
      socket.value.onerror = (error:any) => {
        console.log('连接错误',error);
        setTimeout(() => {
          this.connectWebSocket()
        }, CONNECT_TIME)
      }
    },

    // 发送消息方法
    sendMessage (message: string) {
      this.socket.send(message)
    },

    // 主动断开连接
    handleSocketClose () {
      if (this.socket) {
        this.isReconnect = false
        this.socket.close()
      }
    }
  }
})
